/*********************************************************************************
 *      Copyright:  (C) 2020 YangZhengQing<2489833081@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  socket_init.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(04/05/2020)
 *         Author:  YangZhengQing <2489833081@qq.com>
 *      ChangeLog:  1, Release initial version on "04/05/2020 12:35:03 PM"
 *                 
 ********************************************************************************/

#include"../include/client.h"
 

/* 功能：客户端socket初始化
 * 参数：
 *      serv_IP:传入服务器IP
 *      serv_port:传入服务器端口
 * 返回：成功返回套接字文件描述符，失败返回-1*/
int socket_connect(char *serv_IP,int serv_port)
{
    int                             rv = -1;//函数返回值
    int                             on = 0;//setsockopt参数
    int                             sockfd = -1;//套接字描述符
    struct sockaddr_in              serv_addr;//保存服务器信息结构体

    if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0)
    {
        printf("socket failed: %s\n",strerror(errno));
        return -1;
    }
    
    //设置套接字属性，客户端重启允许再次使用端口IP
    rv = setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
    if(rv < 0)
    {
        printf("setsockopt failed:%s\n",strerror(errno));
        close(sockfd);
        return -1;
    }
    //初始化socket结构体
    memset(&serv_addr,0,sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;//协议族为IPV4
    
    serv_addr.sin_port = htons(serv_port);//本地字节序转化为网络字节序

    rv = inet_aton(serv_IP,&serv_addr.sin_addr);//将点分十进制字符串转化为网络字节序
    if(rv == 0)
    {
        close(sockfd);
        return -1;
    }

    printf("client is connecting serve...\n");

    //默认阻塞模式,大约130s
    if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)//请求连接服务器
    {
        printf("connect failed: %s\n",strerror(errno));
        close(sockfd);
        return -1;
    }
    else
    {

        printf("Connect successfully!\n");
    }

    return sockfd;
 
}
